<template>
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="addRole">新增角色</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="list" stripe border highlight-current-row>
    <el-table-column prop="roleName" label="角色名"/>
    <el-table-column prop="description" label="角色描述"/>
    <el-table-column prop="createdTime" label="创建时间"/>
    <el-table-column prop="updatedTime" label="更新时间"/>
    <el-table-column label="操作" width="400">
      <template #default="scope">
        <el-button type="primary" size="small" @click="editRole(scope.row)">编辑</el-button>
        <el-button type="warning" size="small" @click="editPermission(scope.row)">编辑权限</el-button>
        <el-button type="danger" size="small" @click="deleteRole(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <role-info v-model="visible" v-if="visible" :title="title" :type="type" @save="save" :roleId="roleId"></role-info>
  <resource v-model="visibleResource" v-if="visibleResource" title="编辑权限" :id="roleId"></resource>
</template>

<script>
import { deleteRoleByIdUrl, queryRoleListUrl } from '@/api/api'
import { onBeforeMount, ref } from 'vue'
import { post } from '@/utils/httpRequest'
import RoleInfo from '@/views/roleManage/components/roleInfo'
import Resource from '@/views/roleManage/components/resource'
import { ElMessageBox } from 'element-plus'

export default {
  name: 'roleManage',
  components: {
    Resource,
    RoleInfo
  },
  setup () {
    const list = ref([])
    const visible = ref(false)
    const title = ref('')
    const type = ref(0)
    const roleId = ref('')
    const visibleResource = ref(false)
    const addRole = () => {
      title.value = '新增角色'
      type.value = 0
      roleId.value = ''
      visible.value = true
    }
    const editPermission = (row) => {
      roleId.value = row.id
      visibleResource.value = true
    }
    const deleteRole = async (row) => {
      ElMessageBox.confirm('该角色绑定的所有信息都会被删除！确定删除该角色？', '提示', {
        type: 'warning'
      }).then(async () => {
        const result = await post(deleteRoleByIdUrl, { id: row.id })
        if (result.code === 200) {
          await queryRoleListAsync()
        }
      })
    }
    const editRole = (row) => {
      title.value = '编辑角色'
      type.value = 1
      roleId.value = row.id
      visible.value = true
    }
    const save = () => {
      queryRoleListAsync()
    }
    const queryRoleListAsync = async () => {
      const result = await post(queryRoleListUrl, {})
      if (result.code === 200) {
        list.value = result.data
      }
    }
    onBeforeMount(() => {
      queryRoleListAsync()
    })
    return {
      deleteRole,
      editPermission,
      editRole,
      save,
      addRole,
      visibleResource,
      roleId,
      type,
      title,
      visible,
      list
    }
  }
}
</script>

<style scoped>

</style>
